//
//  YSGNemoSDK.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2022/9/16.
//  Copyright © 2022 tao Tao. All rights reserved.
//

class YSGNemoSDK: NSObject, YSGVideoManagerPotocol {
    
    private let callLoadingCamera = UIImageView()
    
    weak var meetingViewController: YSGMeetingViewController?
    private let queue = DispatchQueue(label: "ysgnemo", qos: .background)
    private let localCanvas = NemoVideoCanvas()
    private var otherCanvas: NemoVideoCanvas?
    private var rosterInfo: NemoRosterInfo?
    
    
    func initSDK() {
        let settings = XYSettings()
        settings.extID = "3e816492058911e7a31d000c29971af5"
        settings.server = "39.172.69.238"
        settings.httpsPort = "7443"
        NemoSDK.sharedInstance().delegate = self
        NemoSDK.sharedInstance().shareNemoSessionSettings(settings)
    }
    func loginSDK(account: String, password: String) {
        NemoSDK.sharedInstance().loginXYLinkAccount(account, password: password)
    }
    func logoutSDK() {
        NemoSDK.sharedInstance().logout()
    }
    func dialNumber(number: String, name: String) {
        guard NemoSDK.sharedInstance().isLogon() else {
            HUDTool.show(message: "登录异常，请重新登录后再次尝试")
            return
        }
        startVideo()
        queue.async {
            let config = NemoCallConfig()
            config.audioMute = false
            config.videoMute = false
            NemoSDK.sharedInstance().makeCall(number, password: "", config: nil)
        }
        DispatchQueue.main.async {
            let vc = YSGMeetingViewController()
            mainWindow.rootViewController?.showDetailViewController(vc, sender: nil)
        }
    }
    func acceptCall() {
        DispatchQueue.main.async {
            let vc = YSGMeetingViewController()
            mainWindow.rootViewController?.showDetailViewController(vc, sender: nil)
        }
        queue.async {
            NemoSDK.sharedInstance().answer()
        }
    }
    func rejectCall() {
        NemoSDK.sharedInstance().reject()
    }
    func hangup() {
//        guard NemoSDK.sharedInstance().isInMeeting() else { return }
        AudioPlayerManager.sharedInstance.stop()
        queue.async {
            NemoSDK.sharedInstance().hangup()
        }
        endVideo()
    }
    func startVideo() {
        queue.async {
            NemoSDK.sharedInstance().enableVideo(true)
            NemoSDK.sharedInstance().enableAudio(ofMic: true)
        }
    }
    func endVideo() {
        queue.async {
            NemoSDK.sharedInstance().enableVideo(false)
            NemoSDK.sharedInstance().enableAudio(ofMic: false)
            NemoSDK.sharedInstance().stopAudio()
        }
    }
    
    func setLocalVideo() {
        guard let vc = meetingViewController else { return }
        let layout = NemoLayout()
        layout.remoteName = UserDefaults.username
        layout.layoutState = .received
        layout.extUserId = "\(UserDefaults.userId)"
        localCanvas.isLocal = true
        localCanvas.view = vc.mineVideoView
        localCanvas.layout = layout
        vc.mineVideoView.layout = layout
    }
    
    func audio(enable: Bool) {
        NemoSDK.sharedInstance().enableVideo(enable)
    }
    func mute(enable: Bool) {
        queue.async {
            NemoSDK.sharedInstance().enableAudio(ofMic: enable)
        }
    }
    func camera(enable: Bool) {
        queue.async {
            NemoSDK.sharedInstance().switchCamera(enable ? .back : .front)
        }
    }
}

extension YSGNemoSDK: NemoSDKDelegate {
    func nemoSDKDidCall(_ number: String, stateChanged callState: NemoCallState, reason: String) {
        switch callState {
        case .disConnected:
            rosterInfo = nil
            otherCanvas?.clear()
            localCanvas.clear()
            MeetingManager.shared.manager?.hangup()
            meetingViewController?.dismiss(animated: true)
            meetingViewController?.status = .disConnected
            AudioPlayerManager.sharedInstance.stop()
        case .connected:
            NemoSDK.sharedInstance().startAudio()
            AudioPlayerManager.sharedInstance.stop()
            meetingViewController?.status = .connected
        case .connecting:
            NemoSDK.sharedInstance().setupVideo(localCanvas)
            AudioPlayerManager.sharedInstance.play()
            meetingViewController?.status = .connecting
        default:
            AudioPlayerManager.sharedInstance.stop()
            meetingViewController?.status = .none
            break
        }
    }
    func nemoSDKDidVideoStateChanged(_ state: NemoVideoState) {
        print("1")
    }
    
    func nemoSDKDidVideoChanged(_ videos: [NemoLayout]) {
        guard let vc = meetingViewController,
              let layout = videos.first else { return }
        let canvas = NemoVideoCanvas()
        otherCanvas = canvas
        canvas.isLocal = false
        canvas.layout = layout
        canvas.view = vc.otherVideoView
        vc.otherVideoView.layout = layout
        NemoSDK.sharedInstance().setupVideo(canvas)
    }
    
    func nemoSDKDidRosterChanged(_ rosters: NemoRosters) {
        guard rosterInfo == nil else { return }
        guard let rosterInfo = rosters.peopleRosters.first as? NemoRosterInfo else { return }
        self.rosterInfo = rosterInfo
        let info = NemoCustomLayoutInfo()
        info.participantId = rosterInfo.participantId
        info.resolution = ._720P
        info.priority = .normal
        info.quality = .normal
        NemoSDK.sharedInstance().setCustomLayout([info])
    }
    
    func nemoSDKDid(inOutNotice noticeInfos: [NemoInOutNotice]) {
        print(noticeInfos)
    }
    
    func nemoSDKDidAccountWasKickOut() {
        meetingViewController?.handUpButtonClick()
    }
    
    func nemoSDKDidReceiveCall(_ number: String, displayName: String, isValid: Bool) {
        guard isValid else { return }
        let alert = UIAlertController(title: "来电", message: displayName, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "拒绝", style: .destructive, handler: { _ in
            self.rejectCall()
        }))
        alert.addAction(UIAlertAction(title: "接听", style: .default, handler: { _ in
            self.acceptCall()
        }))
        UIApplication.lastViewcontroller()?.showDetailViewController(alert, sender: nil)
    }
}
